package com.ruoyi.SpringWebSocket;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: 吕宇宏
 * @Date: 2024/6/26 11:29
 */
@Component
@Slf4j
public class MyWsInterceptor extends HttpSessionHandshakeInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        log.info("开始握手：{}");
//        request.getHeaders().get()
        // 获取HTTP请求中的Cookie头部
        String cookieHeader = request.getHeaders().getFirst("Cookie");

        Map<String,Object> cookiess  = new ConcurrentHashMap<>();
        // 如果存在Cookie头部，则解析它
        if (cookieHeader != null) {
            // 这里只是一个简单的示例，实际上你可能需要使用一个库来正确解析cookie字符串
            // cookieHeader的格式通常是 "key1=value1; key2=value2; ..."

            // 你可以按需要处理cookie字符串，例如，按分号分隔并解析每个键值对
            String[] cookies = cookieHeader.split("; ");
            for (String cookie : cookies) {
                String[] parts = cookie.split("=");
                if (parts.length == 2) {
                    String cookieName = parts[0];
                    String cookieValue = parts[1];
                    // 在这里处理每个cookie的名称和值，例如将它们存储在attributes中
                    cookiess.put(cookieName, cookieValue);
                }
            }
        }
        //進行token解析
        String token = (String) cookiess.get("Admin-Token");
        LoginUser loginUserIdByToken = tokenService.getLoginUserIdByToken(token);

        attributes.put("userId",loginUserIdByToken.getUserId());
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        log.info("握手结束：{}");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
